/**
 * 
 */
package au.edu.swin.videoshop.posapp.ui.sections;

import java.util.List;

import javax.ejb.EJB;
import javax.faces.component.UIData;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;

import au.edu.swin.videoshop.bean.Store;
import au.edu.swin.videoshop.service.StoreService;

/**
 * @author julie
 *
 */
public class StoreSection {
	private Store mSelectedStore;
	private String mMode;
	private List mStores;
	
	@EJB
	private StoreService mStoreService;
	
	public StoreSection() {
	}

	
	/**
	 * @return the stores
	 */
	public List getStores() {
		if (mStores == null) {
			mStores = mStoreService.findAllStores();
		}
		return mStores;
	}

	/**
	 * @return the selectedStore
	 */
	public Store getSelectedStore() {
		return mSelectedStore;
	}

	/**
	 * @param selectedStore the selectedStore to set
	 */
	public void setSelectedStore(Store selectedStore) {
		mSelectedStore = selectedStore;
	}

	public String add() {
		mSelectedStore = new Store();
		mMode = "add";
		return "add";
	}
	
	public String edit() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		UIViewRoot root = facesContext.getViewRoot();
		UIData table = (UIData)root.findComponent("storeForm").findComponent("storeTable");
		mSelectedStore = (Store) table.getRowData();
		mMode = "edit";
		return "edit";
	}
	
	public String save() {
		if (mSelectedStore != null) {
			if (mMode.equals("add")) {
				mStoreService.addStore(mSelectedStore);
			}
			else if (mMode.equals("edit")) {
				mStoreService.updateStore(mSelectedStore);
			}
			
			mStores = null;
		}
		
		return "browse";
	}
	
	public String delete() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		UIViewRoot root = facesContext.getViewRoot();
		UIData table = (UIData)root.findComponent("storeForm").findComponent("storeTable");
		Store store = (Store) table.getRowData();
		mStoreService.markDeleteStore(store.getStoreId());
		
		mStores = mStoreService.findAllStores();
		
		return null;
	}
}
